'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 获取对手列表
 * @author agl
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var configUtil = require('../../../../util/configUtil');
var PlayerManager = require('../../../../libs/playerManager');
var dataApi = require('../../../../libs/dataApi.js');
var taskService = require('../../../../services/taskService');
var roleService = require('../../../../services/roleService');
var arenaConf = require('../../../../config/arenaConf.js');
var arenaModel = require('../../../../models/arenaModel.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var rival_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['arena', 'build', 'role'],
                    cb
                );
            },
            function (cb) {
                var arena_model = player_manager.arena;
                var my_rank = arena_model.rank;
                var range_conf = arenaConf.getRangeConf(my_rank);
                var rank_list = [];
                if (my_rank < 4) {
                    for (var i = 1; i <= 4; i++) {
                        if (i !== my_rank) {
                            rank_list.push(i);
                        }
                    }
                } else {
                    rank_list = _getRankList(my_rank, range_conf[0].refresh_per);
                }

                arenaModel.findByRank(rank_list, cb);
            },
            function (list, cb) {
                _getRoleInfoForRank(list, cb);
            },
            function (rl, cb) {
                rival_list = rl;
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {
                    rival_list: rival_list
                }
            });
        }
    );
};

/**
 * 取出排名列表
 */
var _getRankList = function (start_rank, range_per) {
    var range_size = Math.floor(start_rank * range_per / 100);
    if (range_size < 1) {
        range_size = 1;
    }
    var rank_list = [];
    for (var i = 0; i < 3; i++) {
        if (range_size <= 1) {
            rank_list.push(start_rank - 1);
        } else {
            var rand_rank = _.random(start_rank - range_size, start_rank - 1);
            rank_list.push(rand_rank);
        }

        start_rank -= range_size;
    }

    return rank_list;
};

/**
 * 按排名取出角色信息
 */
var _getRoleInfoForRank = function (rank_list, callback) {
    var result_list = [];
    async.eachSeries(rank_list, function (rank_item, cb) {
        if (rank_item.npc_id === 0) {
            _getRivalRoleInfo(rank_item.role_id, rank_item.def_soldier_list, function (err, role_info) {
                if (!!err) {
                    console.error(err);
                    return cb();
                }
                if (!!role_info) {
                    var result_item = _.clone(role_info, true);
                    result_item.rank = rank_item.rank;
                    result_item.def_power = rank_item.def_power;
                    result_list.push(result_item);
                } else {
                    console.error('not found', rank_item.role_id);
                }
                cb();
            });
        } else {
            _getRivalNpcInfo(rank_item.npc_id, function (err, role_info) {
                role_info.rank = rank_item.rank;
                role_info.def_power = rank_item.def_power;
                result_list.push(role_info);
                cb();
            });
        }
    }, function (err) {
        if (!!err) {
            console.error(err);
            return callback(err);
        }
        callback(null, result_list);
    });
};

/**
 * 取出角色相关信息
 */
var _getRivalRoleInfo = function (role_id, soldier_type_list, callback) {
    var rival_player_manager = new PlayerManager(role_id);
    var soldier_list = [];
    var rival_info;
    async.waterfall(
        [
            function (cb) {
                rival_player_manager.getModel(['soldier'], cb);
            },
            function (cb) {
                var soldier_model = rival_player_manager.soldier;
                _.forEach(soldier_type_list, function (soldier_type) {
                    if (soldier_type > 0) {
                        var soldier_info = soldier_model.getSoldier(soldier_type);
                        if (!!soldier_info) {
                            soldier_list.push({
                                soldier_type: soldier_type,
                                soldier_lvl: soldier_info.lv,
                                soldier_star: soldier_info.star
                            });
                        } else {
                            console.warn('invalid soldier_type:', soldier_type);
                        }
                    }
                });
                cb();
            },
            function (cb) {
                roleService.getRoleInfo(role_id, cb);
            },
            function (info, cb) {
                rival_info = info;
                rival_info.def_soldier_list = soldier_list;
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                return callback(err);
            }

            return callback(null, rival_info);
        }
    );
};

/**
 * 取出NPC信息
 */
var _getRivalNpcInfo = function (npc_id, callback) {
    var rival_info = {};
    var npc_info = arenaConf.getArenaConf(npc_id);
    rival_info.role_id = npc_id;
    rival_info.name = npc_info.name;
    rival_info.lv = npc_info.lvl;
    rival_info.job_type = npc_info.job_type;

    rival_info.def_soldier_list = _getSoldierTypeLvlList(npc_info.soldier_info);

    callback(null, rival_info);
};

/**
 * 获取士兵类型与等级信息
 * @return {Array} [description]
 */
var _getSoldierTypeLvlList = function (soldier_info_str) {
    var soldier_type_list = [];
    if (soldier_info_str.length <= 0) {
        return soldier_type_list;
    }

    var soldier_info_list = soldier_info_str.split(',');
    _.forEach(soldier_info_list, function (soldier_info_item) {
        var soldier_info = soldier_info_item.split(':');
        var soldier_type = parseInt(soldier_info[0]);
        var soldier_lvl = parseInt(soldier_info[1]);
        var soldier_star = parseInt(soldier_info[2]);

        soldier_type_list.push({
            soldier_type: soldier_type,
            soldier_lvl: soldier_lvl,
            soldier_star: soldier_star
        });
    });
    return soldier_type_list;
};
